<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions 
 * @package    Seaocore
 * @copyright  Copyright 2009-2010 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Core.php 2010-11-18 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Seaocore_Api_Invite extends Core_Api_Abstract {

   //THIS FUNCTION IS USED TO SAVE THE FRIEND REQUEST, AND PERFORM ALLIED ACTIONS FOR NOTIFICATION UPDATES, ETC.
  public function addAction($id) {
	  $view = Zend_Registry::isRegistered('Zend_View') ? Zend_Registry::get('Zend_View') : null;

  	// Get id of friend to add
  	$user_id = $id;
  	if (null == $user_id) {
  	  $view->status = false;
  	  $view->error = Zend_Registry::get('Zend_Translate')->_('No member specified');
  	  return;
  	}
  
  	$viewer = Engine_Api::_()->user()->getViewer();
  	$user = Engine_Api::_()->user()->getUser($user_id);
  
  	// check that user is not trying to befriend 'self'
  	if ($viewer->isSelf($user)) {
  	  return;
  	}
  
  	// check that user is already friends with the member
  	if ($user->membership()->isMember($viewer)) {
  	  return;
  	}
  
  	// check that user has not blocked the member
  	if ($viewer->isBlocked($user)) {
  	  return;
  	}

  	// Process
  	$db = Engine_Api::_()->getDbtable('membership', 'user')->getAdapter();
  	$db->beginTransaction();

	 try {
  	  // check friendship verification settings
  	  // add membership if allowed to have unverified friendships
  	  //$user->membership()->setUserApproved($viewer);
  	  // else send request
  	  $user->membership()->addMember($viewer)->setUserApproved($viewer);
  
  
  	  // send out different notification depending on what kind of friendship setting admin has set
  	  /* ('friend_accepted', 'user', 'You and {item:$subject} are now friends.', 0, ''),
  	    ('friend_request', 'user', '{item:$subject} has requested to be your friend.', 1, 'user.friends.request-friend'),
  	    ('friend_follow_request', 'user', '{item:$subject} has requested to add you as a friend.', 1, 'user.friends.request-friend'),
  	    ('friend_follow', 'user', '{item:$subject} has added you as a friend.', 1, 'user.friends.request-friend'),
  	   */


  	  // if one way friendship and verification not required
  	  if (!$user->membership()->isUserApprovalRequired() && !$user->membership()->isReciprocal()) {
  		// Add activity
  		Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $viewer, 'friends_follow', '{item:$object} is now following {item:$subject}.');
  
  		// Add notification
  		Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_follow');
  
  		$message = "You are now following this member.";
  	  }
  
  	  // if two way friendship and verification not required
  	  else if (!$user->membership()->isUserApprovalRequired() && $user->membership()->isReciprocal()) {
  		// Add activity
  		Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $viewer, 'friends', '{item:$object} is now friends with {item:$subject}.');
  		Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $user, 'friends', '{item:$object} is now friends with {item:$subject}.');
  
  		// Add notification
  		Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_accepted');
  	  }
  
  	  // if one way friendship and verification required
  	  else if (!$user->membership()->isReciprocal()) {
  		// Add notification
  		Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_follow_request');
  	  }
  
  	  // if two way friendship and verification required
  	  else if ($user->membership()->isReciprocal()) {
  		// Add notification
  		Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_request');
  	  }
  	  $view->status = true;
  	  $db->commit();
  	} catch (Exception $e) {
  	  $db->rollBack();
  	  $view->status = false;
  	  $view->exception = $e->__toString();
  	}
  }
  
  
  public function sendInvites($recipients) { 
      set_time_limit(0);
      $view = Zend_Registry::isRegistered('Zend_View') ? Zend_Registry::get('Zend_View') : null;
    	$user = Engine_Api::_()->user()->getViewer();
    	$settings = Engine_Api::_()->getApi('settings', 'core');
    	$translate = Zend_Registry::get('Zend_Translate');
    	$message = $view->translate(Engine_Api::_()->getApi('settings', 'core')->invite_message);
    	$message = trim($message);
    	$inviteOnlySetting = $settings->getSetting('user.signup.inviteonly', 0);
    	if (is_array($recipients) && !empty($recipients)) {
    	  // Initiate objects to be used below
    	  $table = Engine_Api::_()->getDbtable('invites', 'invite');
    	  $db = $table->getAdapter();
    	  // Iterate through each recipient
    	  //$already_members       = Engine_Api::_()->invite()->findIdsByEmail($recipients);
    	  //$this->already_members = Engine_Api::_()->user()->getUserMulti($already_members);
    	  $emailsSent = 0;
    
    	  foreach ($recipients as $recipient) {
    		// perform tests on each recipient before sending invite
    		$recipient = trim($recipient);
    		// watch out for poorly formatted emails
    		if (!empty($recipient)) {
    		  // Passed the tests, lets start inserting database entry
    		  // generate unique invite code and confirm it truly is unique
    		  do {
    			$inviteCode = substr(md5(rand(0, 999) . $recipient), 10, 7);
    		  } while (null !== $table->fetchRow(array('code = ?' => $inviteCode)));
    		  // Friend Inviter: Functions starts from here.
    		  $row = $table->createRow();
    		  $row->user_id = $user->getIdentity();
    		  $row->recipient = $recipient;
    		  $row->code = $inviteCode;
    		  $row->timestamp = new Zend_Db_Expr('NOW()');
    		  $row->message = $message;
    		  $row->save();
    		  try {
    			$coremodule = Engine_Api::_()->getDbtable('modules', 'core')->getModule('core');
    			$coreversion = $coremodule->version;
    			if ($coreversion < '4.1.8') {
    			  $inviteUrl = ( _ENGINE_SSL ? 'https://' : 'http://' )
    					  . $_SERVER['HTTP_HOST']
    					  . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
    						  'module' => 'invite',
    						  'controller' => 'signup',
    							  ), 'default', true)
    					  . '?'
    					  . http_build_query(array('code' => $inviteCode, 'email' => $recipient))
    			  ;
    			} else {
    			  $inviteUrl = Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
    						  'module' => 'invite',
    						  'controller' => 'signup',
    							  ), 'default', true)
    					  . '?'
    					  . http_build_query(array('code' => $inviteCode, 'email' => $recipient))
    			  ;
    			}
    
    			$message = str_replace('%invite_url%', $inviteUrl, $message);
    
    			// Send mail
    			$mailType = ( $inviteOnlySetting == 2 ? 'invite_code' : 'invite' );
    			$mailParams = array(
    				'host' => $_SERVER['HTTP_HOST'],
    				'email' => $recipient,
    				'date' => time(),
    				'sender_email' => $user->email,
    				'sender_title' => $user->getTitle(),
    				'sender_link' => $user->getHref(),
    				'sender_photo' => $user->getPhotoUrl('thumb.icon'),
    				'message' => $message,
    				'object_link' => $inviteUrl,
    				'code' => $inviteCode,
    			);
    
    			Engine_Api::_()->getApi('mail', 'core')->sendSystem(
    					$recipient,
    					$mailType,
    					$mailParams
    			);
    			$db->commit();
    		  } catch (Exception $e) {
    			// Silence
    			if (APPLICATION_ENV == 'development') {
    			  throw $e;
    			}
    			continue;
    		  }
    		  $emailsSent++;
    		} // end if (!array_key_exists($recipient, $already_members))
    	  } // end foreach ($recipients as $recipient)
    	} // end if (is_array($recipients) && !empty($recipients))
    
    	if (isset($user->invites_used)) {
    	  $user->invites_used += $emailsSent;
    	}
    	$user->save();
    	return;
  }

}

?>